<template>
  <a-modal
    v-model:open="open"
    title="创建同步任务"
    width="900px"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      class="sync-task-form"
    >
      <!-- 基础信息 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="任务名称" name="task_name">
            <a-input
              v-model:value="formData.task_name"
              placeholder="请输入任务名称"
              :maxlength="200"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="同步模式" name="sync_mode">
            <a-select
              v-model:value="formData.sync_mode"
              placeholder="请选择同步模式"
              @change="handleSyncModeChange"
            >
              <a-select-option
                v-for="option in syncModeOptions"
                :key="option.value"
                :value="option.value"
              >
                <a-tag :color="option.color">{{ option.label }}</a-tag>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="任务描述">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入任务描述（可选）"
          :rows="2"
          :maxlength="500"
          show-count
        />
      </a-form-item>

      <!-- 数据源信息 -->
      <a-divider>数据源配置</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据源">
            <a-input
              :value="dataSource?.name"
              disabled
              placeholder="请先选择数据源"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="源表名称" name="source_table">
            <a-select
              v-model:value="formData.source_table"
              placeholder="请选择源表"
              show-search
              :filter-option="filterTableOption"
              :loading="loadingTables"
              @change="handleSourceTableChange"
            >
              <a-select-option
                v-for="table in availableTables"
                :key="table"
                :value="table"
              >
                {{ table }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 同步配置 -->
      <a-divider>同步配置</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="批次大小" name="batch_size">
            <a-input-number
              v-model:value="formData.batch_size"
              placeholder="请输入批次大小"
              :min="1"
              :max="10000"
              style="width: 100%"
            />
            <div class="form-help-text">
              建议值：100-1000，大批次可提高性能但会增加内存使用
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="任务状态">
            <a-switch
              v-model:checked="formData.is_active"
              checked-children="启用"
              un-checked-children="禁用"
            />
            <div class="form-help-text">
              禁用后任务将不会自动执行
            </div>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 定时配置 -->
      <div v-if="formData.sync_mode === 'scheduled'">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="定时表达式" name="schedule_expression">
              <a-input-group compact>
                <a-select
                  v-model:value="cronExample"
                  placeholder="选择示例"
                  style="width: 200px"
                  @change="handleCronExampleChange"
                >
                  <a-select-option
                    v-for="example in cronExamples"
                    :key="example.value"
                    :value="example.value"
                  >
                    {{ example.label }}
                  </a-select-option>
                </a-select>
                <a-input
                  v-model:value="formData.schedule_expression"
                  placeholder="或输入自定义 cron 表达式"
                  style="width: calc(100% - 200px)"
                />
              </a-input-group>
              <div class="form-help-text">
                格式：分 时 日 月 星期，例如：0 2 * * * 表示每天凌晨2点执行
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 同步过滤条件 -->
      <a-form-item label="同步过滤条件">
        <a-textarea
          v-model:value="formData.sync_filter"
          placeholder="请输入 WHERE 条件（可选），例如：status = 'active' AND created_at > '2024-01-01'"
          :rows="2"
          :maxlength="1000"
        />
        <div class="form-help-text">
          只同步满足条件的数据，留空表示同步所有数据
        </div>
      </a-form-item>

      <!-- 字段映射 -->
      <a-divider>
        <span>
          字段映射
          <a-button
            type="link"
            size="small"
            @click="handleAutoMapping"
            :disabled="!formData.source_table"
          >
            <template #icon><ThunderboltOutlined /></template>
            自动映射
          </a-button>
        </span>
      </a-divider>

      <div class="field-mapping-section">
        <a-table
          :columns="mappingColumns"
          :data-source="formData.field_mappings"
          :pagination="false"
          size="small"
          row-key="id"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'source_field'">
              <div class="source-field-display">
                <span class="field-name-primary">{{ record.source_field }}</span>
                <span v-if="record.source_comment" class="field-comment-text">
                  （{{ record.source_comment }}）
                </span>
              </div>
            </template>
            <template v-if="column.key === 'target_field'">
              <a-select
                v-model:value="record.target_field"
                placeholder="选择目标字段"
                style="width: 200px"
                @change="handleTargetFieldChange(record, $event)"
              >
                <a-select-option
                  v-for="field in targetFieldOptions"
                  :key="field.value"
                  :value="field.value"
                >
                  {{ field.label }}
                </a-select-option>
              </a-select>
            </template>
            <template v-if="column.key === 'field_type'">
              <a-select
                v-model:value="record.field_type"
                placeholder="字段类型"
                style="width: 120px"
              >
                <a-select-option
                  v-for="type in fieldTypeOptions"
                  :key="type.value"
                  :value="type.value"
                >
                  {{ type.label }}
                </a-select-option>
              </a-select>
            </template>
            <template v-if="column.key === 'is_required'">
              <a-switch
                v-model:checked="record.is_required"
                size="small"
              />
            </template>
            <template v-if="column.key === 'default_value'">
              <a-input
                v-model:value="record.default_value"
                placeholder="默认值"
                size="small"
              />
            </template>
            <template v-if="column.key === 'actions'">
              <a-button
                type="link"
                danger
                size="small"
                @click="handleRemoveMapping(index)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>

        <div class="mapping-actions">
          <a-button type="dashed" @click="handleAddMapping" block>
            <template #icon><PlusOutlined /></template>
            添加字段映射
          </a-button>
        </div>
      </div>

      <!-- 预览区域 -->
      <a-divider v-if="formData.field_mappings.length > 0">同步预览</a-divider>

      <div v-if="formData.field_mappings.length > 0" class="preview-section">
        <a-alert
          :message="`已配置 ${formData.field_mappings.length} 个字段映射`"
          type="info"
          show-icon
        >
          <template #description>
            <div class="preview-content">
              <p><strong>源表：</strong>{{ formData.source_table }}</p>
              <p><strong>同步模式：</strong>{{ getSyncModeText(formData.sync_mode) }}</p>
              <p><strong>预计同步字段：</strong></p>
              <ul class="field-list">
                <li v-for="mapping in formData.field_mappings" :key="mapping.id">
                  {{ mapping.source_field }} → {{ mapping.target_field }}
                  <a-tag size="small" :color="getFieldTypeColor(mapping.field_type)">
                    {{ mapping.field_type }}
                  </a-tag>
                  <a-tag v-if="mapping.is_required" size="small" color="red">必需</a-tag>
                </li>
              </ul>
            </div>
          </template>
        </a-alert>
      </div>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, ThunderboltOutlined } from '@ant-design/icons-vue'
import syncApi from '@/apis/sync_api'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  dataSource: {
    type: Object,
    default: null
  },
  initialData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:open', 'success'])

// 响应式数据
const formRef = ref()
const loading = ref(false)
const loadingTables = ref(false)
const availableTables = ref([])
const cronExample = ref('')

// 表单数据
const formData = reactive({
  task_name: '',
  description: '',
  data_source_id: '',
  source_table: '',
  sync_mode: 'manual',
  schedule_expression: '',
  batch_size: 1000,
  sync_filter: '',
  is_active: true,
  field_mappings: []
})

// 选项数据
const syncModeOptions = syncApi.getSyncModeOptions()
const fieldTypeOptions = syncApi.getFieldTypeOptions()
const cronExamples = syncApi.getCronExpressionExamples()
const targetFieldOptions = [
  { label: '对象名称 (name)', value: 'name' },
  { label: '唯一编码 (code)', value: 'code' },
  { label: '对象类型 (object_type)', value: 'object_type' },
  { label: '型号 (model)', value: 'model' },
  { label: '所属单位 (organization)', value: 'organization' },
  { label: '部署状态 (deployment_status)', value: 'deployment_status' },
  { label: '探测距离 (detection_range)', value: 'detection_range' },
  { label: '响应时间 (response_time)', value: 'response_time' },
  { label: '精度 (accuracy)', value: 'accuracy' },
  { label: '感知能力 (perception_capability)', value: 'perception_capability' },
  { label: '通信能力 (communication_capability)', value: 'communication_capability' },
  { label: '适用场景 (applicable_scenarios)', value: 'applicable_scenarios' },
  { label: '地理位置 (location)', value: 'location' },
  { label: '类型特定数据 (type_specific_data)', value: 'type_specific_data' }
]

// 表格列配置
const mappingColumns = [
  {
    title: '源字段',
    dataIndex: 'source_field',
    key: 'source_field',
    width: 220
  },
  {
    title: '目标字段',
    key: 'target_field',
    width: 200
  },
  {
    title: '字段类型',
    key: 'field_type',
    width: 120
  },
  {
    title: '必需',
    key: 'is_required',
    width: 60
  },
  {
    title: '默认值',
    key: 'default_value',
    width: 150
  },
  {
    title: '操作',
    key: 'actions',
    width: 60
  }
]

// 表单验证规则
const rules = {
  task_name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 1, max: 200, message: '名称长度为1-200个字符', trigger: 'blur' }
  ],
  sync_mode: [
    { required: true, message: '请选择同步模式', trigger: 'change' }
  ],
  source_table: [
    { required: true, message: '请选择源表', trigger: 'change' }
  ],
  batch_size: [
    { required: true, message: '请输入批次大小', trigger: 'blur' },
    { type: 'number', min: 1, max: 10000, message: '批次大小范围为1-10000', trigger: 'blur' }
  ],
  schedule_expression: [
    {
      validator: (rule, value) => {
        if (formData.sync_mode === 'scheduled' && !value) {
          return Promise.reject('定时同步模式必须提供定时表达式')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const open = computed({
  get: () => props.open,
  set: (value) => emit('update:open', value)
})

// 监听器
watch(() => props.dataSource, (newSource) => {
  if (newSource && props.open) {
    formData.data_source_id = newSource.id
    loadAvailableTables()
  }
})

watch(() => props.initialData, (newData) => {
  if (newData) {
    // 填充初始数据
    if (newData.source_table) {
      formData.source_table = newData.source_table
    }
    if (newData.field_mappings && newData.field_mappings.length > 0) {
      formData.field_mappings = newData.field_mappings.map(mapping => ({
        ...mapping,
        id: generateId()
      }))
    }
  }
})

watch(() => props.open, (newValue) => {
  if (newValue) {
    resetForm()
    if (props.dataSource) {
      formData.data_source_id = props.dataSource.id
      loadAvailableTables()
    }
  }
})

// 方法
const resetForm = () => {
  Object.assign(formData, {
    task_name: '',
    description: '',
    data_source_id: props.dataSource?.id || '',
    source_table: '',
    sync_mode: 'manual',
    schedule_expression: '',
    batch_size: 1000,
    sync_filter: '',
    is_active: true,
    field_mappings: []
  })
  cronExample.value = ''

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

const loadAvailableTables = async () => {
  if (!props.dataSource) return

  try {
    loadingTables.value = true

    const response = await syncApi.testConnection(props.dataSource.id)

    if (response && (response.success || response.available_tables)) {
      availableTables.value = response.available_tables || []
    } else {
      message.warning('获取表列表为空，请检查数据源连接')
      availableTables.value = []
    }
  } catch (error) {
    message.error('获取表列表失败：' + (error.message || '未知错误'))
    availableTables.value = []
  } finally {
    loadingTables.value = false
  }
}

const filterTableOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const handleSyncModeChange = (value) => {
  if (value !== 'scheduled') {
    formData.schedule_expression = ''
    cronExample.value = ''
  }
}

const handleCronExampleChange = (value) => {
  formData.schedule_expression = value
}

const handleSourceTableChange = async (tableName) => {
  if (!tableName || !props.dataSource) return

  try {
    // 获取表结构用于自动映射建议
    const tableStructure = await syncApi.getTableStructure(props.dataSource.id, tableName)

    // 清空现有映射
    formData.field_mappings = []

    // 自动映射建议
    tableStructure.columns.forEach(column => {
      const suggestedField = suggestTargetField(column.name)
      if (suggestedField) {
        formData.field_mappings.push({
          id: generateId(),
          source_field: column.name,
          source_comment: column.comment || '', // 保存字段注释
          target_field: suggestedField.field,
          field_type: suggestedField.type,
          is_required: !column.nullable || suggestedField.required,
          default_value: column.default || ''
        })
      }
    })
  } catch (error) {
    console.error('获取表结构失败：', error)
  }
}

const suggestTargetField = (sourceField) => {
  const lowerField = sourceField.toLowerCase()

  const suggestions = {
    'name': { field: 'name', type: 'string', required: true },
    'code': { field: 'code', type: 'string', required: true },
    'type': { field: 'object_type', type: 'string', required: true },
    'model': { field: 'model', type: 'string', required: false },
    'organization': { field: 'organization', type: 'string', required: false },
    'status': { field: 'deployment_status', type: 'string', required: false },
    'range': { field: 'detection_range', type: 'float', required: false },
    'response_time': { field: 'response_time', type: 'float', required: false },
    'accuracy': { field: 'accuracy', type: 'float', required: false }
  }

  for (const [key, suggestion] of Object.entries(suggestions)) {
    if (lowerField.includes(key)) {
      return suggestion
    }
  }

  return null
}

const handleAutoMapping = () => {
  if (!formData.source_table) {
    message.warning('请先选择源表')
    return
  }

  handleSourceTableChange(formData.source_table)
  message.success('自动映射完成')
}

const handleAddMapping = () => {
  formData.field_mappings.push({
    id: generateId(),
    source_field: '',
    source_comment: '', // 添加注释字段
    target_field: '',
    field_type: 'string',
    is_required: false,
    default_value: ''
  })
}

const handleRemoveMapping = (index) => {
  formData.field_mappings.splice(index, 1)
}

const handleTargetFieldChange = (record, targetField) => {
  const fieldConfig = targetFieldOptions.find(field => field.value === targetField)
  if (fieldConfig) {
    // 根据目标字段设置合适的类型
    const typeMap = {
      'name': 'string',
      'code': 'string',
      'object_type': 'string',
      'model': 'string',
      'organization': 'string',
      'deployment_status': 'string',
      'detection_range': 'float',
      'response_time': 'float',
      'accuracy': 'float',
      'perception_capability': 'json',
      'communication_capability': 'json',
      'applicable_scenarios': 'json',
      'location': 'json',
      'type_specific_data': 'json'
    }

    record.field_type = typeMap[targetField] || 'string'

    // 重要字段默认为必需
    const requiredFields = ['name', 'code', 'object_type']
    record.is_required = requiredFields.includes(targetField)
  }
}

const getSyncModeText = (mode) => {
  const option = syncModeOptions.find(opt => opt.value === mode)
  return option ? option.label : mode
}

const getFieldTypeColor = (type) => {
  const colorMap = {
    'string': 'blue',
    'integer': 'green',
    'float': 'orange',
    'boolean': 'purple',
    'datetime': 'cyan',
    'json': 'red'
  }
  return colorMap[type] || 'default'
}

const validateFieldMappings = () => {
  if (formData.field_mappings.length === 0) {
    throw new Error('请至少配置一个字段映射')
  }

  const errors = []
  formData.field_mappings.forEach((mapping, index) => {
    if (!mapping.source_field) {
      errors.push(`第 ${index + 1} 个映射的源字段不能为空`)
    }
    if (!mapping.target_field) {
      errors.push(`第 ${index + 1} 个映射的目标字段不能为空`)
    }
    if (!mapping.field_type) {
      errors.push(`第 ${index + 1} 个映射的字段类型不能为空`)
    }
  })

  if (errors.length > 0) {
    throw new Error(errors.join('; '))
  }

  // 检查是否有重复的目标字段
  const targetFields = formData.field_mappings.map(m => m.target_field)
  const uniqueTargets = [...new Set(targetFields)]
  if (targetFields.length !== uniqueTargets.length) {
    throw new Error('目标字段不能重复')
  }

  return true
}

const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate()

    // 验证字段映射
    validateFieldMappings()

    loading.value = true

    await syncApi.createSyncTask(formData)
    message.success('同步任务创建成功')
    emit('success')
  } catch (error) {
    if (typeof error === 'string') {
      message.error(error)
    } else if (error.response?.data?.detail) {
      message.error(error.response.data.detail)
    } else {
      message.error('创建失败：' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  open.value = false
}
</script>

<style scoped>
.sync-task-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-help-text {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.field-mapping-section {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-top: 16px;
}

.mapping-actions {
  margin-top: 12px;
}

.preview-section {
  margin-top: 16px;
}

.preview-content {
  margin-top: 8px;
}

.preview-content p {
  margin-bottom: 8px;
}

.field-list {
  margin: 8px 0;
  padding-left: 20px;
}

.field-list li {
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ant-divider-horizontal.ant-divider-with-text) {
  margin: 20px 0;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-table-thead > tr > th) {
  background: #f5f5f5;
  font-weight: 600;
}

:deep(.ant-input-group .ant-select) {
  z-index: 1;
}

/* 源字段显示样式 */
.source-field-display {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  gap: 0;
  padding: 4px 0;
}

.field-name-primary {
  font-weight: 500;
  color: #1890ff;
  font-size: 14px;
}

.field-comment-text {
  font-size: 12px;
  color: #8c8c8c;
  margin-left: 2px;
}

/* 源字段选项样式（已废弃） */
.source-field-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.source-field-option .field-name {
  font-weight: 500;
  color: #333;
}

.source-field-option .field-comment {
  font-size: 12px;
  color: #999;
  font-style: italic;
}

/* 源字段注释样式（已废弃，使用下拉选择） */
.source-field-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.source-comment {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.info-icon {
  color: #1890ff;
  font-size: 14px;
  cursor: help;
}

.comment-text {
  font-style: italic;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>